from cloudinary.models import CloudinaryField
from django.contrib.auth.models import AbstractUser
from django.db import models


class User(AbstractUser):
    """扩展用户模型"""
    USER_TYPE_CHOICES = (
        ('normal', '普通用户'),
        ('admin', '管理员'),
        ('super_admin', '超级管理员'),
    )
    
    user_type = models.CharField(max_length=20, choices=USER_TYPE_CHOICES, default='normal', verbose_name='用户类型')
    phone = models.CharField(max_length=20, unique=True, null=True, blank=True, verbose_name='手机号')
    # avatar = models.ImageField(upload_to='avatars/', null=True, blank=True, verbose_name='头像')
    # 用户头像配置 - 专门用于头像
    avatar = CloudinaryField(
        '头像',   # 第一个参数就是 verbose_name
        folder='meet/users/avatars/',  # 专门的头像文件夹
        # transformation=[
        #     {
        #         'width': 150,
        #         'height': 150,
        #         'crop': 'fill',
        #         'gravity': 'face',
        #         'quality': 'auto:good'
        #     }
        # ],
        # format='jpg',
        blank=True,
        null=True,
    )
    nickname = models.CharField(max_length=50, blank=True, verbose_name='昵称')
    signature = models.TextField(max_length=200, blank=True, verbose_name='个性签名')
    interests = models.CharField(max_length=500, blank=True, verbose_name='兴趣标签')
    
    # 隐私设置
    show_phone = models.BooleanField(default=False, verbose_name='公开手机号')
    show_email = models.BooleanField(default=False, verbose_name='公开邮箱')
    show_activities = models.BooleanField(default=True, verbose_name='公开活动记录')
    
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='注册时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')
    
    class Meta:
        db_table = 'users'
        verbose_name = '用户'
        verbose_name_plural = '用户'
    
    def __str__(self):
        return self.nickname or self.username
    
    def is_admin_user(self):
        """判断是否为管理员或超级管理员"""
        return self.user_type in ['admin', 'super_admin']
    
    def is_super_admin_user(self):
        """判断是否为超级管理员"""
        return self.user_type == 'super_admin'

    # 头像
    # def get_avatar_url(self):
    #     """获取头像URL，带优化参数"""
    #     if self.avatar:
    #         return self.avatar.build_url(
    #             width=150,
    #             height=150,
    #             crop="fill",
    #             gravity="face",
    #             quality="auto",
    #             format="auto"
    #         )
    #     # 如果用户没有头像,返回默认头像URL
    #     return self.get_default_avatar_url()
    #     # return self.get_default_avatar_url('/static/imgs/default-avatar.jpg')
    def get_avatar_url(self):
        """获取头像URL，带优化参数"""
        if self.avatar:
            try:
                # 尝试使用 Cloudinary 的优化URL
                return self.avatar.build_url(
                    # width=150,
                    # height=150,
                    # crop="fill",
                    # gravity="face",
                    # quality="auto",
                    # format="auto"
                )
            except Exception:
                # 如果 Cloudinary 配置有问题，回退到原始URL
                try:
                    return self.avatar.url
                except Exception:
                    # 如果连原始URL都获取失败，返回默认头像
                    return self.get_default_avatar_url()
        # 如果用户没有头像,返回默认头像URL
        return self.get_default_avatar_url()

    def get_default_avatar_url(self):
        """获取默认头像URL"""
        return '/static/imgs/default-avatar.jpg'

    def delete_avatar(self):
        """删除头像文件"""
        if self.avatar:
            self.avatar.delete()
            self.avatar = None
            self.save()


class PasswordResetCode(models.Model):
    """密码重置验证码"""
    user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='用户')
    code = models.CharField(max_length=6, verbose_name='验证码')
    email = models.EmailField(null=True, blank=True, verbose_name='邮箱')
    phone = models.CharField(max_length=20, null=True, blank=True, verbose_name='手机号')
    is_used = models.BooleanField(default=False, verbose_name='是否已使用')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    expires_at = models.DateTimeField(verbose_name='过期时间')
    
    class Meta:
        db_table = 'password_reset_codes'
        verbose_name = '密码重置验证码'
        verbose_name_plural = '密码重置验证码'
    
    def __str__(self):
        return f"{self.user.username} - {self.code}"
